/*
 * @Author: caihongtai caihongtai
 * @Date: 2025-02-08 21:23:21
 * @LastEditors: caihongtai caihongtai
 * @LastEditTime: 2025-03-18 10:48:43
 * @FilePath: /ai-interview-vue/src/router/index.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import Layout from '@/components/Layout/index.vue'
import { profileChildRoutes } from './modules/profile'
import { loginRoutes } from './modules/login'
import { agreementRoutes } from './modules/agreement'
import { interviewRoutes } from './modules/interview'
import { useUserStore } from '@/store/modules/user'
import { userApi } from '@/api/user'

const routes = [
    {
        path: '/',
        redirect: '/home'
    },
    {
        path: '/home',
        component: Layout,
        children: [
            {
                path: '/home',
                name: 'Home',
                component: () => import('@/views/Home/index.vue'),
                meta: {
                    keepAlive: true
                }
            },
            {
                path: 'interview',
                name: 'Interview',
                component: () => import('@/views/Interview/index.vue')
            },
            // 主页面路由（在底部tab显示）
            {
                path: '/profile/mine',
                name: 'Profile',
                component: () => import('@/views/Profile/mine/index.vue'),
            }
        ]
    },
    ...profileChildRoutes,
    ...loginRoutes,
    ...agreementRoutes,
    ...interviewRoutes
]

// 改用 history 模式
// history: createWebHistory(),
const router = createRouter({
    history: createWebHashHistory(),
    base: '/ai-interview-vue/',
    routes
})

router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore()
    const token = localStorage.getItem('token')

    // 如果有token但没有用户信息，说明可能是刷新页面导致的
    // if (token && !userStore.userInfo) {
    //     try {
    //         // 获取用户信息
    //         await userStore.setUserInfo()
    //     } catch (error) {
    //         console.error('获取用户信息失败:', error)
    //         // 如果获取用户信息失败，可能是token过期
    //         localStorage.removeItem('token')
    //     }
    // }

    // 如果没有token且不是登录页面，尝试自动登录
    if (!token && to.path !== '/login' && to.path !== '/verify') {
        try {
            // 尝试自动登录
            const loginResult = await userApi.getAnonymousToken()
            // if (loginResult.code === 0 && loginResult.data?.access_token) {
            //     // 设置token
            localStorage.setItem('token', loginResult.data.access_token)
            //     // 获取用户信息
            //     await userStore.setUserInfo()
            // }
        } catch (error) {
            console.error('自动登录失败:', error)
        }
    }

    // 需要登录的页面
    // const requiresAuth = ['/profile/mine', '/interview']

    // if (requiresAuth.some(path => to.path.startsWith(path)) && !userStore.loginStatus) {
    //     next('/login')
    // } else {
    //     next()
    // }
    next()
})

export default router 